<template>
  <div id="add_user">
    <h2>添加用户</h2>
    <el-form class="add_form" ref="form" :model="newUserObj" label-width="80px" label-position="top">
      <el-form-item label="用户名">
        <el-input v-model="newUserObj.username"></el-input>
      </el-form-item>
      <el-form-item label="密码">
        <el-input type="password" v-model="newUserObj.password"></el-input>
      </el-form-item>
      <el-form-item label="确认密码">
        <el-input type="password" v-model="newUserObj.againPassword"></el-input>
      </el-form-item>
      <el-form-item label="用户头像">
        <el-upload
            class="avatar-uploader"
            :action="`${baseUrl}/api/image/uploadImage`"
            :show-file-list="false"
            :on-success="handleAvatarSuccess">
          <img v-if="newUserObj.avatar" :src="newUserObj.avatar" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-button @click="addUser" type="primary">添加</el-button>
    </el-form>
  </div>
</template>

<script>
import baseUrl from "../const/baseUrl";
import {addUser} from "../network/userApi";

export default {
  name: "AddUser",
  data(){
    return{
      baseUrl,
      newUserObj:{
        avatar:"https://oss.yhuayi.com/sixth-qianfeng/back/weidenglu.png"
      },
    }
  },
  methods: {
    //头像上传成功
    handleAvatarSuccess(res) {
      this.newUserObj.avatar = res.data;
    },
    addUser() {
      if (this.newUserObj.password === this.newUserObj.againPassword) {
        addUser(this.newUserObj).then((result) => {
          console.log(result);
          if (result.data.code === 200) {
            this.$message({
              message: '添加用户成功!',
              type: 'success'
            });
            sessionStorage.setItem("wlj-url", "/usermanage");
            this.$router.push("/blankpage");
          } else {
            this.$message({
              message: '添加用户失败!',
              type: 'warning'
            });
          }
        }).catch((reason)=>{
          console.log(reason);
        })
      }else{
        this.$message({
          message: '两次密码不相同!',
          type: 'warning'
        });
      }
    }
  }
}
</script>

<style scoped>
.add_form{
  width: 70%;
  margin: 30px auto;
  text-align: left;
}
/*头像*/
.avatar{
  height: 150px;
}
</style>
